package com.xixun.rainfall.tools;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.xixun.joey.uart.BytesData;
import com.xixun.joey.uart.IUartListener;
import com.xixun.joey.uart.IUartService;
import com.xixun.rainfall.App;
import com.xixun.rainfall.ui.MainActivity;

import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Watchable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @Author： LJH
 * @Time： 2024/5/30
 * @description：
 */
public class UartTool {
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static Executor executor2 = Executors.newSingleThreadExecutor();
    private static int count = 0;//1对应水位，2对应小时雨量，3对应今日雨量
    private static final int WATER_LEVEL = 1;
    private static final int HOURLY_RAINFALL = 2;
    private static final int DAILY_RAINFALL = 3;
    public static void receivePackage(String port, IUartService uart)                //接收协议包
    {
        try {
            Log.i("TAG", "==============准备监听uart，进行read()==============");
//            uart.config(port,9600);      //设置波特率
            //监听port，接收数据
            uart.read(port, new IUartListener.Stub() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onReceive(BytesData data) throws RemoteException {
                    int len = data.getData().length;
//                    Log.i("TAG", "长度为,length:" + len+",string:"+Arrays.toString(data.getData()));
                    if (len == 13){
                        String msg = showBytes(data.getData(), 0);
                        ++count;
                        if (count>3){
                            count = 1;
                        }
                        App.logD(msg+",count:"+count);
                        int data1 = washUartData(data.getData());
                        switch (count){
                            case WATER_LEVEL:
                                BigDecimal bigDecimal = new BigDecimal(String.valueOf(data1));
                                BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                                App.getApp().waterLevelSave(divide.toString());
                                App.logD("水位level："+divide);
                                App.getApp().getMainViewModel().changeWaterLevel(divide.toString());
                                break;
                            case HOURLY_RAINFALL:
                                BigDecimal hRainBigDecimal = new BigDecimal(String.valueOf(data1));
                                BigDecimal divide2 = hRainBigDecimal.divide(new BigDecimal("10"));
                                App.getApp().hourlyRainfallSave(divide2.toString());
                                App.logD("小时雨量hour："+divide2);
                                App.getApp().getMainViewModel().changeHourlyRainfall(divide2.toString());
                                break;
                            case DAILY_RAINFALL:
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(data1));
                                BigDecimal divide3 = bigDecimal3.divide(new BigDecimal("10"));
                                App.getApp().dailyRainfallSave(divide3.toString());
                                App.logD("今日雨量day："+divide3);
                                App.getApp().getMainViewModel().changeDailyRainFall(divide3.toString());
                                break;
                        }
                        App.logD("data:"+data1);
                    }
                }
            });

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 清洗串口数据，获取到需要的内容
     * @param data
     * @return
     */
    private static int washUartData(byte[] data){
        byte[] bytes1 = convertPlcDataToComputerData(new byte[]{data[7], data[8]});
        byte[] bytes2 = convertPlcDataToComputerData(new byte[]{data[9], data[10]});
        byte[] bytes3 = new byte[]{bytes1[0],bytes1[1],bytes2[0],bytes2[1]};
        return convertPlcDataToInteger(bytes3);
    }

    // 将PLC数据转换为十进制整数
    public static int convertPlcDataToInteger(byte[] data) {
        // 检查数据长度
        if (data.length != 4) {
            throw new IllegalArgumentException("PLC数据长度必须为4字节");
        }

        // 创建一个ByteBuffer，并设置字节序为小端序（与电脑存储方式一致）
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        // 将PLC数据写入ByteBuffer
        buffer.put(data);

        // 获取十进制整数
        return buffer.getInt(0);
    }

    // 将PLC数据转换为电脑存储数据
    public static byte[] convertPlcDataToComputerData(byte[] data) {
        // 检查数据长度
        if (data.length != 2) {
            throw new IllegalArgumentException("PLC数据长度必须为2字节");
        }

        // 创建一个新的字节数组用于存储电脑存储数据
        byte[] computerData = new byte[2];

        // 将PLC数据进行字节交换（交叉交换）
        computerData[0] = data[1];
        computerData[1] = data[0];

        return computerData;
    }


    public static String showBytes(byte[] msg, int len) {
        StringBuilder show = new StringBuilder("");
        int showNum = 0;
        int iData = 0;

//        if ((null != title) && (!title.equals(""))) {
//            show.append(title + ": ");
//        } else {
//            show.append("Hex: ");
//        }
        if (null != msg) {
            showNum = (0 == len)? msg.length: len;
            if (showNum > msg.length) {
                showNum = msg.length;
            }
            for (int i = 0; i < showNum; ++i) {
                iData = msg[i] & 0xff;
                if (iData < 16) {
                    show.append('0');
                }
                show.append(Integer.toHexString(iData).toUpperCase());
                show.append(' ');
            }
        } else {
            show.append("");
        }
        String s = formatStr(show.toString());
        App.logD(s);
        String[] s1 = s.split(" ");
        show.delete(0,show.length());
        show.append(s1[7]);
        show.append(s1[8]);
        show.append(s1[9]);
        show.append(s1[10]);

//        String substring = formatStr(show.toString()).trim().substring(15, 23);
        return show.toString();
    }

    private static String formatStr(String msg) {
        StringBuilder show=new StringBuilder("");
        show.append(msg);
        for (int index = 70; index < show.length(); index += 70) {
            if (' ' == show.charAt(index - 1)) {
                show.insert(index - 1, '\n');
            } else if (' ' == show.charAt(index - 2)) {
                show.insert(index - 2, '\n');
            } else {
                show.insert(index, '\n');
            }
        }
        return show.toString();
    }

    /**
     * 字节数组转换成十六进制字符串
     * @param b 字节数组
     * @param split 分隔字符串，主要用于输出调试
     * @return
     */
    public static String byteToHexStr(byte[] b,int len, String split) {
        String hs="";
        String stmp="";
        for (int n=0;n<len;n++) {
            stmp=(Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) hs=hs+"0"+stmp;
            else hs=hs+stmp;
            hs = hs + split;
        }
        return hs.toUpperCase();
    }


    public static void sendPackage(final byte[] packageSP, final String port, final IUartService uart)    //发送协议包
    {
        try {
            uart.write(port, packageSP);      //发送数据
//            Log.i("TAG", "协议包发送完毕");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

}
